package com.gintama.common.aspect;

import com.gintama.common.annotation.TraceLogLimit;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 类型跟踪日志限制切面。
 *
 */
@Aspect
@Component
@Slf4j
public class TraceLogLimitAspect {

    @Pointcut("@annotation(com.gintama.common.annotation.TraceLogLimit)")
    public void pointCut(){
        log.info("进入日志限制切点");
    }

    /**
     * 后置处理.
     *
     * @param joinPoint 连接点
     */
    @After("pointCut()")
    public void after(JoinPoint joinPoint){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            log.info("非接口请求触发方法，无需进行traceLog过滤");
            return;
        }
        HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();
        final MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        TraceLogLimit logLimit = signature.getMethod().getAnnotation(TraceLogLimit.class);
        response.addHeader(TraceLogLimit.RESPONSE_HEAD_TRACE_LOG_LIMIT, Integer.toString(logLimit.maxLength()));
        log.info("设置log最长字符{}", logLimit.maxLength());
    }


}
